<?php
/**
 * 
 * 金库类
 * @author will
 *
 */
class Money {
	/**
	 * 获取金库数据
	 * @param <int> $uin
	 * @param <string> $type
	 */
	public static function get($uin , $type = false) {
		$Db = loadDB();
		$result = $Db->getOne("SELECT * FROM `money` WHERE `uin` = " . $uin);
		
		// 如果金库数据不存在，则新写入一条数据
		if($result === false) {
			$query_data = array(
				'uin' => $uin,
				'gold' => 0,
				'level' => 1,
				'time' => 0,
			);
			$Db->doInsert('money' , $query_data);
			
			$result = $query_data;
		}
		
		return empty($type) ? $result : $result[$type];
	}
	
	/**
	 * 添加钱
	 * @param <int> $uin
	 * @param <string> $type
	 * @param <int> $num
	 */
	public static function update($uin , $num) {
		$Db = loadDB();
		
		$money = self::get($uin);
		$next_num = $money['gold'] + $num;
		
		// 检查上限
		$check_bound = self::checkBound($money['level'] , $next_num);
		if($check_bound) {
			return $check_bound;
		}

		if($next_num < 0) {
			$next_num = 0;
		}
		
		$query_data = array(
			'gold' => $next_num,
			'time' => isset($_SERVER['REQUEST_TIME']) ? $_SERVER['REQUEST_TIME'] : time(),
		);
		
		$success = $Db->doUpdate('money' , $query_data , "`uin` = {$uin}");
		
		return $success ? 0 : 601;
	} 
	
	/**
	 * 判断上限
	 * @param <string> $type
	 * @param <int> $level
	 * @param <int> $num
	 */
	public static function checkBound($level , $num) {
		return 0;
	}
	
	/**
	 * 获取金库容量
	 * Enter description here ...
	 */
	public static function getCapacity($level) {
		$capacity = array();
		
		switch ($level) {
			case 1: $capacity = array( 'gold' => 99900 , 'upgrade' => 50000 ); break;
			case 2: $capacity = array( 'gold' => 299900 , 'upgrade' => 100000 ); break;
			case 3: $capacity = array( 'gold' => 699900 , 'upgrade' => 200000 ); break;
			case 4: $capacity = array( 'gold' => 999900 , 'upgrade' => 500000 ); break;
			case 5: $capacity = array( 'gold' => 2999900 , 'upgrade' => -1 ); break;
		}
		
		return $capacity;
	}
	
	/**
	 * 将数字换转为文字格式
	 * @param <array> $money
	 */
	public static function toString($money) {
		$gold = isset($money['gold']) ? $money['gold'] : 0;
		
		$str_arr = array();
		if($gold > 0) $str_arr[] = $gold . '金币';
		
		if(empty($str_arr)) {
			$str_arr[] = '一个铜板都没有';
		}
		
		return implode('' , $str_arr);
	}
	
	/**
	 * 获取排行榜
	 * @param <string> $type
	 * @param <int> $offset
	 * @param <int> $limit
	 */
	public static function getTopList($offset = 0 , $limit = 10) {
		$Db = loadDB();
		
		$result = $Db->getAll("SELECT `uin` , `gold` FROM `money` ORDER BY `gold` DESC LIMIT {$offset} , {$limit}");
		return $result;
	}
	
	
	public static function upgrade() {
	
	}
	
}

# end of script
